package com.snail.snailvr.utils;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.player.Definition;
import com.snail.snailvr.player.PlayActivity;
import com.snail.snailvr.player.uiutils;
import com.snail.snailvr.views.BaseActivity;
import com.snail.snailvr.views.adapter.SingleChoiceAdapter;
import com.snail.snailvr.widget.seekbar.DiscreteSeekBar;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subjects.PublishSubject;

/**
 * //TODO 参数过长的都改掉 改成builder类型
 * 对话框集合类
 * Created by snail on 16/4/19.
 */
public class DialogUtils {
    /**
     * show basic dialog
     * @param activity activity
     * @param titleString 标题
     * @param contentString 内容
     * @param negative 取消按钮
     * @param positive 去顶按钮
     * @param isWarning 是否警告
     * @param submitListener 确定事件
     * @return
     */
    public static void showBasicDialog(Activity activity, String titleString,
                                       String contentString, String negative, String positive,
                                       boolean isWarning, final View.OnClickListener submitListener) {
        View view = LayoutInflater.from(activity).inflate(R.layout.basic_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity).setView(view).create();

        TextView title = (TextView) view.findViewById(R.id.basic_dialog_title);
        title.setText(titleString);

        TextView content = (TextView) view.findViewById(R.id.basic_dialog_content);
        content.setText(contentString);

        TextView submit = (TextView) view.findViewById(R.id.btn_submit);
        submit.setText(positive);

        TextView cancel = (TextView) view.findViewById(R.id.btn_cancle);
        cancel.setText(negative);

        if(!isWarning)
            submit.setTextColor(activity.getResources().getColor(R.color.positive_normal_color));
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                submitListener.onClick(v);
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
        dialog.show();
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        dialog.getWindow()
                .setLayout(dm.widthPixels,
                        activity.getResources().getDimensionPixelSize(R.dimen.basic_dialog_height));
    }

    /**
     * 显示带有输入框的对话框
     * @param activity activity
     * @param titleString 标题
     * @param contentString 内容
     * @param negative 取消按钮
     * @param positive 去顶按钮
     * @param isWarning 是否警告
     * @param submitListener 确定事件
     * @return
     */
    public static void showInputDialog(final Activity activity, final boolean isLive, String titleString,
                                       final String contentString, String hintString, String negative,
                                       String positive, boolean isWarning, final View.OnClickListener submitListener) {
        View view = LayoutInflater.from(activity).inflate(R.layout.input_dialog, null);

        final AlertDialog dialog = new AlertDialog.Builder(activity).setView(view).create();

        TextView title = (TextView) view.findViewById(R.id.basic_dialog_title);
        title.setText(titleString);

        final TextView content = (TextView) view.findViewById(R.id.basic_dialog_content);
        content.setText(contentString);

        final TextView submit = (TextView) view.findViewById(R.id.btn_submit);
        submit.setText(positive);

        TextView cancel = (TextView) view.findViewById(R.id.btn_cancle);
        cancel.setText(negative);

        final EditText urlEdit = (EditText) view.findViewById(R.id.url);
        urlEdit.setHint(hintString);

        if (!isWarning)
            submit.setTextColor(activity.getResources().getColor(R.color.feedback_text_color));

        final PublishSubject<String> publishSubject=PublishSubject.create();
        publishSubject.debounce(400, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {

                if(TextUtils.isEmpty(s)){
                    submit.setEnabled(false);
                    submit.setTextColor(activity.getResources().getColor(R.color.feedback_text_color));
                }else{
                    submit.setEnabled(true);
                    submit.setTextColor(activity.getResources().getColor(R.color.positive_normal_color));
                }
            }
        });

        urlEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                publishSubject.onNext(s.toString());
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url=urlEdit.getText().toString().trim();
                boolean isUrlInvalid=false;
                if(isLive){
                    if (!Util.isLiveUrl(url)){
                        isUrlInvalid=true;
                        content.setText(activity.getString(R.string.hint_live_url));
                    }
                }else{
                    if (!Util.isHttpUrl(url)){
                        isUrlInvalid=true;
                        content.setText(activity.getString(R.string.invalid_url));
                    }
                }
                if(isUrlInvalid){
                    content.setTextColor(activity.getResources().getColor(R.color.invalid_live_url_color));
                    urlEdit.setBackground(activity.getResources().getDrawable(R.drawable.url_error_edit_text));
                    urlEdit.startAnimation(AnimationUtil.getSharkAnimation());
                    Observable.timer(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            content.setText(contentString);
                            content.setTextColor(activity.getResources().getColor(R.color.toolbar_title_color));
                            urlEdit.setBackground(activity.getResources().getDrawable(R.drawable.url_edit_text));
                        }
                    });
                    return;
                }
                view.setTag(url);
                if(submitListener!=null)
                    submitListener.onClick(view);
                dialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();


        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        dialog.getWindow()
                .setLayout(dm.widthPixels,
                        activity.getResources().getDimensionPixelSize(R.dimen.input_dialog_height));
    }

    public static AlertDialog showSingleChoiceDialog(Activity activity, String titleString,
                                                     String[] contentArrays, final View.OnClickListener onItemClickListener, int choicePosition){
        View view = LayoutInflater.from(activity).inflate(R.layout.sinagle_choice_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity,R.style.SingleChoiceDialog).setView(view).create();

        TextView title = (TextView) view.findViewById(R.id.dialog_title);
        title.setText(titleString);

        ListView contentListView = (ListView) view.findViewById(R.id.single_choice_list);
        final SingleChoiceAdapter adapter=new SingleChoiceAdapter(activity, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onItemClickListener!=null)
                    onItemClickListener.onClick(v);
                dialog.dismiss();
            }
        }, contentArrays, choicePosition);
        contentListView.setAdapter(adapter);

//        TextView submit = (TextView) view.findViewById(R.id.btn_submit);
//        submit.setText(positive);

        TextView cancel = (TextView) view.findViewById(R.id.btn_cancle);
//        cancel.setText(negative);


//        submit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                v.setTag(adapter.getChoicePosition());
//                onClickListener.onClick(v);
//                dialog.dismiss();
//            }
//        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
            }
        });

        dialog.show();
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        dialog.getWindow().setLayout(Util.dip2px(activity,330), dm.heightPixels-activity.getResources().getDimensionPixelSize(R.dimen.wifi_transfer_40dp));
        return dialog;

    }

    public static void showSelectFovDialog(final Activity activity, DiscreteSeekBar.OnProgressChangeListener progressChangeListener,final View.OnClickListener submitListener,final View.OnClickListener onCancelListener) {
        View view = LayoutInflater.from(activity).inflate(R.layout.select_fov_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity,R.style.SingleChoiceDialog).setView(view).create();
        final DiscreteSeekBar discreteSeekBar=(DiscreteSeekBar)view.findViewById(R.id.discrete);
        discreteSeekBar.setOnProgressChangeListener(progressChangeListener);
        discreteSeekBar.setValue(uiutils.getPreferenceKeyIntValue(activity, Definition.KEY_FOV, PlayActivity.FOV_DEFAULT));
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int discreteSeekBarWidth=dm.widthPixels-activity.getResources().getDimensionPixelSize(R.dimen.dimen_330)
                -activity.getResources().getDimensionPixelSize(R.dimen.padding_16);

        int bestAngleWidth=discreteSeekBarWidth/7;

        TextView minAngle = (TextView) view.findViewById(R.id.best_min_angle);

        TextView maxAngle = (TextView) view.findViewById(R.id.best_max_angle);

        RelativeLayout.LayoutParams minAngleParams=(RelativeLayout.LayoutParams) minAngle.getLayoutParams();
        RelativeLayout.LayoutParams maxAngleParams=(RelativeLayout.LayoutParams) maxAngle.getLayoutParams();
        if(minAngleParams!=null&&maxAngleParams!=null) {
            int marginLeft=discreteSeekBarWidth * 2 / 7+activity.getResources().getDimensionPixelSize(R.dimen.padding_16);
            minAngleParams.leftMargin=marginLeft;
            maxAngleParams.leftMargin=marginLeft+bestAngleWidth/2+activity.getResources().getDimensionPixelSize(R.dimen.padding_12);
        }

        final TextView submit = (TextView) view.findViewById(R.id.btn_submit);

        TextView cancel = (TextView) view.findViewById(R.id.btn_cancle);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setTag(discreteSeekBar.getValue());
                uiutils.setPreferenceKeyIntValue(activity, Definition.KEY_FOV, discreteSeekBar.getValue());
                dialog.dismiss();
                submitListener.onClick(v);
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                if(onCancelListener!=null)
                    onCancelListener.onClick(view);
            }
        });

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if(onCancelListener!=null)
                    onCancelListener.onClick(null);
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();

        dialog.getWindow().setLayout(Util.dip2px(activity,330), Util.dip2px(activity,236));
    }

    public static boolean showJudgeNetDialog(Activity pActivity, final View.OnClickListener submitListener){
        Activity activity = null;
        if(pActivity != null)
            activity = pActivity;
        else
            activity = BaseActivity.getCurrentActivity();;

        if(NetworkUtil.isNoConnected()){
            if (activity != null)
                ToastUtils.makeToastColorShow(activity, activity.findViewById(android.R.id.content), activity.getString(R.string.no_network_tip));
            return true;
        }else if (NetworkUtil.isMobileDataConnected()){
            if (activity != null)
                DialogUtils.showBasicDialog(activity, activity.getString(R.string.tip_title)
                        , activity.getString(R.string.mobile_network_tip), activity.getString(R.string.str_Cancel)
                        , activity.getString(R.string.str_OK), true,submitListener);
            return true;
        }
        return false;
    }
}
